package com.uchedao.vehicledetection.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.utils.L;
import com.uchedao.mybaselibrary.activity.BaseActivity;
import com.uchedao.mybaselibrary.utils.LogUtil;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.activity.blue_tooth.AnalyticalDFBlueTooth;
import com.uchedao.vehicledetection.activity.blue_tooth.BluetoothTool;
import com.uchedao.vehicledetection.activity.blue_tooth.DeviceListActivity;
import com.uchedao.vehicledetection.activity.blue_tooth.IBluetooth2Listener;
import com.uchedao.vehicledetection.config.AppInfoManager;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.model.Condition;
import com.uchedao.vehicledetection.model.DFEntity;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.PaintThickness;
import com.uchedao.vehicledetection.utils.ToastUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;


public class PaintActivity2Bluetooth extends BaseActivity {


    DecimalFormat df = new DecimalFormat("####.0");
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;

    private ArrayList<PaintThickness> paintThicknessArray;
    private PaintThickness paintThickness;
    private LayoutInflater inflater;
    private PaintAdapter adapter;
    private int index;
    private int nextIndex;// 下一项索引
    private ImageView mBack;
    private TextView hiddenTv;// 标题
    private TextView nextBtn;// 下一项按钮
    private TextView tv_bluetooth_state;// 蓝牙连接
    private ListView listView;

    private WakeLock wakeLock;

    @Override
    protected String getActivityTag() {
        return "PaintActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.paint_detail_pop;
    }

    @Override
    protected void initView() {
        acquireWakeLock();
        BluetoothTool.getInstance().setListener(iBluetooth2Listener);
        paintThicknessArray = ((ArrayList<PaintThickness>) getIntent().getSerializableExtra("PaintThickness"));
        int position = getIntent().getIntExtra("position", 0);
        inflater = LayoutInflater.from(this);

        initAll();

        tv_bluetooth_state = (TextView) findViewById(R.id.tv_bluetooth_state);

        setData(position);

    }

    @Override
    protected void initData() {
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {
            tv_bluetooth_state.setText(getString(R.string.bluetooth_is_not_available));
        } else {
            if (!TextUtils.isEmpty(AppInfoManager.getBluetoothAddress()) && !"null".equals(AppInfoManager.getBluetoothAddress())) {
                if (TextUtils.isEmpty(AppInfoManager.getBluetoothName()) || "null".equals(AppInfoManager.getBluetoothName())) {
                    AppInfoManager.setBluetoothName(AppInfoManager.getBluetoothAddress());
                }
                tv_bluetooth_state.setText(AppInfoManager.getBluetoothName());
                bindBluetooth(AppInfoManager.getBluetoothAddress());
            } else {
                tv_bluetooth_state.setText(getString(R.string.paint_obd_not_conn));
            }
        }
    }

    @Override
    protected void initListener() {

        tv_bluetooth_state.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBluetoothAdapter == null) {
                    showToast(getString(R.string.bluetooth_is_not_available));
                } else {
                    //打开蓝牙
                    if (!mBluetoothAdapter.isEnabled()) {
                        mBluetoothAdapter.enable();
                    }
                    //蓝牙列表
                    Intent serverIntent = new Intent(PaintActivity2Bluetooth.this, DeviceListActivity.class);
                    startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                }
            }
        });
    }

    /**
     * 监听退出
     */
    private OnClickListener exitListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            exit();

        }
    };

    /**
     * 初始化
     */
    private void initAll() {
        hiddenTv = (TextView) findViewById(R.id.paint_detail_hidden_tv);
//		hiddenTv.setOnClickListener(exitListener);
        mBack = (ImageView) findViewById(R.id.paint_detail_hidden_iv);
        mBack.setOnClickListener(exitListener);
        Button retryBtn = (Button) findViewById(R.id.retry_detect_item_btn);
        //重新检测
        retryBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                L.i("paintThickness = " + paintThickness);
                if (paintThickness != null) {
                    for (int i = 0; i < paintThickness.result.size(); i++) {
                        paintThickness.result.set(i, -1);
                        L.i("i=" + paintThickness.result.get(i));
                    }
                    updateDataAndUI();
                }

            }
        });

        mBack = (ImageView) findViewById(R.id.paint_detail_hidden_iv);

        nextBtn = (TextView) findViewById(R.id.detect_next_item_tv);
        nextBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                save();
                // 若无下一项，显示完成
                if (nextIndex == -1)
                    exit();
                else
                    setData(nextIndex);
            }
        });

        listView = (ListView) findViewById(R.id.paint_detail_list2);
        adapter = new PaintAdapter();
        listView.setAdapter(adapter);

    }

    public boolean save() {
        Condition condition = GlobalInfo.draft.condition.clone();
        condition.paint_thickness = paintThicknessArray.toArray(new PaintThickness[0]);
        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

            // 如果VIN值有更改
        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
        }

        // int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
        // // 若原先状态为未完成，且数据已变动，则状态改变为已完成
        // if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
        // Draft.STATUE_FINISH) {
        // values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
        // status = Draft.STATUE_FINISH;
        // }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            return true;
        }

        return false;
    }

    private Gson gson = new Gson();

    /**
     * 不导出无Expose注解的字段
     *
     * @param src
     * @return
     */
    public String toJson(Object src) {
        return gson.toJson(src);
    }

    /**
     * 找到下一检测项
     */
    private int getNextIndex() {
        for (int i = 0; i < paintThicknessArray.size(); i++) {
            if (i != index)
                for (int k : paintThicknessArray.get(i).result) {
                    if (k == -1)
                        return i;
                }
        }
        return -1;
    }

    /**
     * 设置下一项按钮是否可用
     */
    private void initNextBtn(ArrayList<Integer> result) {
        nextIndex = getNextIndex();
        // 若无下一项，显示完成
        if (nextIndex == -1) {
            nextBtn.setText(R.string.complete);
        } else {
            nextBtn.setText(R.string.paint_test_next);
        }

        setNextBtnState(result);
    }

    /**
     * 设置下一项按钮是否可用
     */
    private void setNextBtnState(ArrayList<Integer> result) {
        for (int k : result) {
            L.i("k=" + k);
            if (k == -1) {
                nextBtn.setEnabled(false);
                nextBtn.setTextColor(getResources().getColor(R.color.normal_text_color));
                return;
            }
        }
        nextBtn.setTextColor(getResources().getColor(R.color.alert_blur));
        nextBtn.setEnabled(true);
    }

    /**
     * 设置数据
     */
    private void setData(int index) {
        this.index = index;
        paintThickness = paintThicknessArray.get(index);
        hiddenTv.setText(paintThickness.name);
        initNextBtn(paintThickness.result);
        updateDataAndUI();
        fixListViewHeight(listView);
    }

    /**
     * 数据与UI更新
     */
    private void updateDataAndUI() {
        setValue();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 数值统计
     */
    private void setValue() {
        int max = -1;
        int min = -1;
        int sum = 0;
        int count = 0;
        for (int i : paintThickness.result) {
            if (i != -1) {
                count++;
                sum += i;
                if (i > max)
                    max = i;
                if (min == -1 || i < min)
                    min = i;
            }
        }

        paintThickness.max = max;
        setValue(R.id.max, "最高值", max == -1 ? "" : df.format(((float) max) / 10.0f));
        setValue(R.id.min, "最低值", min == -1 ? "" : df.format(((float) min) / 10.0f));
        setValue(R.id.average, "平均值", max == -1 ? "" : df.format(((float) (sum / count)) / 10.0f));
    }

    private void setValue(int layoutId, String name, String value) {
        LinearLayout layout = (LinearLayout) findViewById(layoutId);
        TextView paint_detail_item_name = (TextView) layout.findViewById(R.id.paint_detail_item_name);
        EditText paint_detail_item_value = (EditText) layout.findViewById(R.id.paint_detail_item_value);
        // paint_detail_item_value.setEnabled(false);
        paint_detail_item_value.setFocusable(false);

        paint_detail_item_name.setText(name);
        paint_detail_item_value.setText(value);
    }

    class MyTextWatcher implements TextWatcher {
        EditText et;

        public MyTextWatcher(EditText et) {
            this.et = et;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int position = (Integer) et.getTag();
            int k = -1;
            if (!TextUtils.isEmpty(s.toString())) {
                try {
                    k = Integer.parseInt(s.toString());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            paintThickness.result.set(position, k);
            setValue();
            for (int i : paintThickness.result) {
                L.i("afterTextChanged i=" + i);
            }
            setNextBtnState(paintThickness.result);
            // adapter.notifyDataSetChanged();

        }
    }

    private class PaintAdapter extends BaseAdapter {
        String[] entries = GlobalInfo.resources.getStringArray(R.array.paint_detail_right_entries);

        @Override
        public int getCount() {
            if (paintThickness == null)
                return 0;
            return paintThickness.points;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        class ViewHolder {
            TextView name;
            EditText value;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = inflater.inflate(R.layout.paint_detail_item, null);
                convertView.setTag(viewHolder);
                viewHolder.name = (TextView) convertView.findViewById(R.id.paint_detail_item_name);
                viewHolder.value = (EditText) convertView.findViewById(R.id.paint_detail_item_value);
//                viewHolder.value.addTextChangedListener(new MyTextWatcher(viewHolder.value));
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            int k = paintThickness.result.get(position);
            viewHolder.value.setTag(position);
            viewHolder.name.setText(entries[position]);
            viewHolder.value.setText(k == -1 ? "" : df.format(((float) k) / 10.0f));

            return convertView;
        }
    }

    public void fixListViewHeight(ListView listView) {
        // 如果没有设置数据适配器，则ListView没有子项，返回。
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (listAdapter == null) {
            return;
        }
        for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
            View listViewItem = listAdapter.getView(index, null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public void exit() {
        Intent data = new Intent();
        data.putExtra("PaintThickness", paintThicknessArray);
        setResult(RESULT_OK, data);
        finish();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.e(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    bindBluetooth(address);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        releaseWakeLock();
        closeBluetooth();
        super.onDestroy();
    }

    /**
     * 关闭蓝牙进程
     */
    private void closeBluetooth() {
        BluetoothTool.getInstance().close();
    }

    /**
     * 绑定蓝牙
     */
    private void bindBluetooth(String address) {
        // Get the BLuetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        AppInfoManager.setBluetoothName(device.getName());
        AppInfoManager.setBluetoothAddress(device.getAddress());
        // Attempt to connect to the device
        BluetoothTool.getInstance().startDF_5000(device.getAddress());
    }

    /**
     * 蓝牙单次读取回来的数据
     */
    private byte[] readBuf;

    private IBluetooth2Listener iBluetooth2Listener = new IBluetooth2Listener() {
        @Override
        public void sendConnectSuccess() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("连接成功");
                    tv_bluetooth_state.setText(String.format("%s:连接成功", AppInfoManager.getBluetoothName()));
                }
            });
        }

        @Override
        public void sendPairingSuccess() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("完成配对");
                    tv_bluetooth_state.setText(String.format("%s:完成配对，正在连接设备中……", AppInfoManager.getBluetoothName()));
                }
            });
        }

        @Override
        public void sendReadData() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("等待接收数据中……");
                    tv_bluetooth_state.setText(String.format("%s:等待接收数据中……", AppInfoManager.getBluetoothName()));
                }
            });
        }

        @Override
        public void sendReadFail() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("读取蓝牙数据失败，重新启动读取线程！");
                    tv_bluetooth_state.setText(String.format("%s:无法读取数据，正在重新连接蓝牙", AppInfoManager.getBluetoothName()));
                    closeBluetooth();
                    BluetoothTool.getInstance().startDF_5000(AppInfoManager.getBluetoothAddress());
                }
            });
        }

        @Override
        public void sendConnectFail() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("连接失败");
                    tv_bluetooth_state.setText(String.format("%s:连接失败", AppInfoManager.getBluetoothName()));
                    closeBluetooth();
                }
            });
        }

        @Override
        public void sendPairingFail() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("配对失败");
                    tv_bluetooth_state.setText(String.format("%s:配对失败", AppInfoManager.getBluetoothName()));
                    closeBluetooth();
                }
            });
        }

        @Override
        public void sendReceiveData(byte[] _readBuf) {
            readBuf = _readBuf;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // construct a string from the valid bytes in the buffer
                    DFEntity dfEntity = AnalyticalDFBlueTooth.AnalyticalDF(readBuf);
                    readBuf = null;
                    if (dfEntity != null && dfEntity.getThickness() != 0) {
                        for (int i = 0; i < paintThickness.result.size(); i++) {
                            if (paintThickness.result.get(i) == -1) {
                                paintThickness.result.set(i, dfEntity.getThickness());
                                break;
                            }
                        }
                        //更新UI
                        updateDataAndUI();
                        setNextBtnState(paintThickness.result);
                    } else {
                        ToastUtil.showToast("数据无效！", true);
                    }
                }
            });
        }
    };

    /**
     * 获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行
     */
    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, getClass()
                    .getCanonicalName());
            if (null != wakeLock) {
                Log.i(TAG, "call acquireWakeLock");
                wakeLock.acquire();
            }
        }
    }

    // 释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock && wakeLock.isHeld()) {
            Log.i(TAG, "call releaseWakeLock");
            wakeLock.release();
            wakeLock = null;
        }
    }
}
